package org.fjsei.yewu.aop.hibernate;

import org.fjsei.yewu.filter.Node;
import org.hibernate.Session;
import org.hibernate.search.engine.backend.document.DocumentElement;
import org.hibernate.search.engine.backend.document.IndexFieldReference;
import org.hibernate.search.mapper.orm.HibernateOrmExtension;
import org.hibernate.search.mapper.pojo.bridge.TypeBridge;
import org.hibernate.search.mapper.pojo.bridge.binding.TypeBindingContext;
import org.hibernate.search.mapper.pojo.bridge.mapping.programmatic.TypeBinder;
import org.hibernate.search.mapper.pojo.bridge.runtime.TypeBridgeWriteContext;

/** # 没用到 @ 只用于 测试的；
 * TypeBinder基本类似于PropertyBinder;
 * 【测试表明】没法让Hibernate Search在重建索引时刻，从Type：Entity身上减少自动生成的SQL的冗长性。 举例如：
 * Company索引对应的，其自身有@OneToOne(mappedBy = "company")  private Unit unit;的属性字段，就会导致HS生成语句必然提取关联Unit对象。
 * 就算改为@OneToOne(mappedBy="company",fetch= FetchType.LAZY) private Unit unit;也是无济于事，照样有提取Unit语句。
 * */
@Deprecated
public class FullNameBinder implements TypeBinder {

    @Override
    public void bind(TypeBindingContext context) {
        context.dependencies().useRootOnly();
//        context.dependencies().use( "firstName" ).use( "lastName" );
        IndexFieldReference<String> fullNameField = context.indexSchemaElement()
                .field( "fullName", f -> f.asString().analyzer( "default" ) )
                .toReference();
        context.bridge(
                Node.class,
                new Bridge(
                        fullNameField
                )
        );
    }

    private static class Bridge implements TypeBridge<Node> {
        private final IndexFieldReference<String> fullNameField;
        private Bridge(IndexFieldReference<String> fullNameField) {
            this.fullNameField = fullNameField;
        }
        //进入本回调函数时，Node author实际上已经装载实体完毕，会生成的多余SQL已经发生了。用Bridge是【无法解决】的。
        @Override
        public void write(DocumentElement target, Node author, TypeBridgeWriteContext context) {
            Session session = context.extension( HibernateOrmExtension.get() ).session();
            String fullName =  "啥个他" ;
            target.addValue( this.fullNameField, fullName );
        }
    }
}


/*用例：
    @Indexed
    @TypeBinding(binder = @TypeBinderRef(type = FullNameBinder.class))
    public class Company｛   ｝
* */
